<template>
    <el-upload
            class="yWeight"
            drag
            action=""
            :accept="fileType"
            :file-list="fileList"
            :auto-upload="false"
            :multiple="maxCount > 1"
            :limit="maxCount"
            :on-change="onChange"
            :on-remove="onRemove"
            :before-upload="beforeAvatarUpload"
    >
        <el-icon class="el-icon--upload">
            <upload-filled/>
        </el-icon>
        <div class="el-upload__text">
            拖动文件到这或<em>点击这里上传</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                <span>可上传</span>
                <span style="color: red">{{ fileType.split(",").join("/") }}</span>
                <span>格式文件，单个小于</span>
                <span style="color: red">{{ maxSize }}M</span>
                <span>，最多可上传</span>
                <span style="color: red">{{ maxCount }}</span>
                <span>个文件</span>
            </div>
        </template>
    </el-upload>
</template>

<script>
import OSS from 'ali-oss'

export default {
    props: {
        fileList: {type: Array, default: []},
        fileType: {type: String, default: ".jpg,.png"},
        maxCount: {type: Number, default: 1},
        maxSize: {type: Number, default: 2}, //单个文件最大体积，单位：M
        ossPath: {type: String, default: "server/default"},
    },
    data() {
        return {
            fileList_out: this.fileList,
        }
    },
    beforeCreate() {
    },
    methods: {
        onChange(file, fileList) {
            this.fileList_out = fileList;
        },
        onRemove(file, fileList) {
            this.fileList_out = fileList;
        },
        beforeAvatarUpload(rawFile) {
            if (rawFile.size / 1024 / 1024 > this.maxSize) {
                this.yFree.yToast(`单个文件不能超过${this.maxSize}MB!`);
                return false;
            }
            return true;
        },
        async upload() {
            if (this.fileList_out.length <= 0) return null;
            this.yFree.yShowProgress(this);
            let images = await new Promise(async (resolve) => {
                try {
                    let client = new OSS({
                        region: 'oss-cn-beijing',
                        accessKeyId: 'LTAI5tRLDfXSxYww3ZjFfWnQ',
                        accessKeySecret: 'Uvb1gKiO9cdgs7mR2D5lPBeOb64JYK',
                        bucket: 'y-yshop',
                    });
                    let results = [];
                    for (const file of this.fileList_out) {
                        results.push(await client.put(`${this.ossPath}/${new Date().getTime()}_${file.name}`, file.raw));
                    }
                    resolve(results);
                } catch (e) {
                    resolve(null);
                }
            });
            this.yFree.yDismissProgress();
            return images;
        },
    },
}
</script>

<style scoped>
</style>
